package com.book.adapter;

import com.alibaba.fastjson.JSONObject;
import com.book.pojo.UserInfo;
import com.book.service.UserService;
import com.book.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

/**
 * @param
 * @author oyz
 * @version 1.0.4
 * @description: 第三方登录适配器类(类适配器)
 * @date 2023/10/24 21:12
 */
@Component
public class Login3rdAdapter extends UserService implements Login3rdTarget {

    @Value("${gitee.state}")
    private String giteeState;

    @Value("${gitee.token.url}")
    private String giteeToken;

    @Value("${gitee.user.prefix}")
    private String giteeUserPrefix;

    @Value("${gitee.user.url}")
    private String giteeUserUrl;






    @Override
    public String loginByGitee(String code, String state) {
        if(!giteeState.equals(state)){
            throw new RuntimeException("invaild state");
        }
        // 请求gitee平台获取token,并携带code
        String tokenUrl = giteeToken.concat(code);
        JSONObject tokenRepose = HttpClientUtils.execute(tokenUrl, HttpMethod.GET);
        String accessToken = String.valueOf(tokenRepose.get("access_token"));
        // 请求gitee平台获取用户信息,并携带token
        String userInfoUrl = giteeUserUrl.concat(accessToken);
        JSONObject userInfoRepose = HttpClientUtils.execute(userInfoUrl, HttpMethod.GET);
        String userName = String.valueOf(userInfoRepose.get("name"));
        String password = userName.concat(giteeUserPrefix);
        return autoRegist3rdAndLogin(userName,password);
    }

    private String autoRegist3rdAndLogin(String userName, String password) {
        // 如果已经登录过了,那么直接登录
        if(checkUserExists(userName)){
            return login(userName, password);
        }
        // 如果第一次登录,那么先注册在登录
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(userName);
        userInfo.setUserPassword(password);
        register(userInfo);
        return login(userName,password);

    }

    @Override
    public String loginByQQ(String... params) {
        return null;
    }

    @Override
    public String loginByWeixin(String... params) {
        return null;
    }
}
